package com.softcits.email.controller;

import java.util.List;
import java.util.Locale;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.softcits.email.job.EmailJob;
import com.softcits.email.model.MailInfo;
import com.softcits.email.service.EmailService;
import com.softcits.email.utils.ResultUtil;


@RestController
@CrossOrigin(origins = "*")
public class EmailController {
    private final static Logger LOGGER = LoggerFactory.getLogger(EmailController.class);
    @Autowired
    private MessageSource source;
    
    @Autowired
    @Qualifier("Scheduler")
    private Scheduler s;
    
    @Autowired
    private EmailService es;

    @RequestMapping(value="/send", method=RequestMethod.POST)
    @ResponseBody
    public Object sendEmail(@ModelAttribute @Validated MailInfo info) throws Exception {
        boolean flag = es.sendEmail(info);
        if(flag) {
            return ResultUtil.success("ok");
        } else {
            return ResultUtil.error("Fail");
        }
    }
    
    @PostMapping("/sendbyscheduler")
    public MailInfo sendEmailByScheduler(@RequestBody @Validated MailInfo info) throws Exception {
        LOGGER.debug(info.getExpression());
        
        JobKey jobKey = JobKey.jobKey("email01", "egroup01");
        
        TriggerKey triggerKey = TriggerKey.triggerKey("etrigger01", "egroup01");
        if(this.s.checkExists(jobKey)) {
            this.s.pauseTrigger(triggerKey);
            this.s.unscheduleJob(triggerKey);
            this.s.deleteJob(jobKey);
        }
        
        JobDetail job = JobBuilder.newJob(EmailJob.class).withIdentity(jobKey).build();
        List<String> toList = info.getToAddress();
        
        StringBuilder buf = new StringBuilder();
        for(String to : toList) {
            buf.append(to);
            
            buf.append(",");
        }
        
        
        job.getJobDataMap().put("toAddress", buf.toString());
        job.getJobDataMap().put("subject", info.getSubject());
        job.getJobDataMap().put("content", info.getContent());
        
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(
                CronScheduleBuilder.cronSchedule(info.getExpression()).withMisfireHandlingInstructionDoNothing())
                .build();

        // Tell quartz to schedule the job using our trigger
        s.scheduleJob(job, trigger);

        return info;
    }
    
    @GetMapping("/msg/{language}/{key}")
    public String getMessage(@PathVariable String language, @PathVariable String key) {
        Locale locale = Locale.getDefault();
        if(language != null && !"".equals(language)){
            String[] split = language.split("_");
            locale = new Locale(split[0],split[1]);
        } 
        
        String value = source.getMessage(key, null, locale);
        return value;
    }
    
    
    @GetMapping("/toAddresses")
    public List<String> getToEmailAddresses() {
        List<String> list = this.es.getAllEmailAddresses();
        return list;
    }
}
